package com.vng.zing.lib;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author tiepvv
 */
public class ProfilerLog {

    public String funcName;
    public long nanoTime;
    public List<ProfilerLog> profiler = new ArrayList<ProfilerLog>();
    public boolean isDebug = false;
    public static final ProfilerLog DISABLE_PORFILER_LOG = new ProfilerLog(false);

    public static ProfilerLog getProfiler(HttpServletRequest req) {
        if (getDebug(req)) {
            return new ProfilerLog(true);
        }
        return DISABLE_PORFILER_LOG;
    }

    public static ProfilerLog getProfiler(boolean isDebug) {
        if (isDebug) {
            return new ProfilerLog(true);
        }
        return DISABLE_PORFILER_LOG;
    }

    public ProfilerLog(boolean isDebug) {
        this.isDebug = isDebug;
    }

    public ProfilerLog(String fName, long naoTime) {
        funcName = fName;
        nanoTime = naoTime;
    }

    public void log(String funcName, long nanoTiem) {
        if (isDebug) {
            profiler.add(new ProfilerLog(funcName, nanoTiem));
        }
    }

    public String renderLog() {
        if (isDebug) {
            String str = "<table border='1' cellspacing='5' cellpadding='5' style='border-collapse:collapse'><tbody>";
            str += "<tr><th width='50'>No.</th><th>Func</th><th>Time elapsed in msecs</th></tr>";
            int index = 0;
            for (Iterator<ProfilerLog> it = profiler.iterator(); it.hasNext();) {
                ProfilerLog obj = it.next();
                str += String.format("<tr><th width='50'>%s</th><th>%s</th><th>%s</th></tr>", index, obj.funcName, (float) obj.nanoTime / 1000000);
                index++;
            }
            str += "</tbody></table>";
            return str;
        }
        return "";
    }

    private static boolean getDebug(HttpServletRequest req) {
        String debug = req.getParameter("debug");
        if (debug != null && debug.equals("true")) {
            return true;
        } else {
            return false;
        }
    }
}
